/*
 * @author zzr
 * @date: 2025/10/12  15:40
 * @description: 删除倒数第 K 个节点
 */
public class Demo7 {
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null || n <= 0) {
            return head;
        }
        // 创建哑节点
        ListNode dummy = new ListNode(0);
        dummy.next = head;

        ListNode fast = dummy;
        ListNode slow = dummy; // slow 从哑节点触发，可以找到待删元素的前一个节点

        for (int i = 0; i < n; i++) {
            if (fast.next == null) {
                return head;
            }
            fast = fast.next;
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        // 此时 slow 指向的是倒数第 K 个节点的前一个节点
        slow.next = slow.next.next;
        return dummy.next;
    }
}
